import React, { useEffect, useState } from "react";
import {
  Card,
  Row,
  Col,
  Select,
  Table,
  Tag,
  Progress,
  Space,
  Button,
  Typography,
  Tooltip,
} from "antd";
import {
  BarChartOutlined,
  LineChartOutlined,
  PieChartOutlined,
  DownloadOutlined,
} from "@ant-design/icons";
import * as echarts from "echarts";
import styled from "styled-components";

const { Title, Text } = Typography;
const { Option } = Select;

const StyledCard = styled(Card)`
  margin-bottom: 24px;
  .ant-card-head-title {
    font-weight: bold;
  }
`;

const ChartContainer = styled.div`
  height: 400px;
  width: 100%;
`;

interface KnowledgePoint {
  name: string;
  mastery: number;
  exercises: number;
  errorRate: number;
}

interface Student {
  id: string;
  name: string;
  averageScore: number;
  attendance: number;
  exercises: number;
  performance: string;
}

const TeacherAnalysis: React.FC = () => {
  const [selectedClass, setSelectedClass] = useState<string>("class1");
  const [selectedTimeRange, setSelectedTimeRange] = useState<string>("month");

  useEffect(() => {
    // 初始化知识点掌握度热力图
    const masteryChart = echarts.init(document.getElementById("masteryChart"));
    const masteryOption = {
      title: {
        text: "知识点掌握度分布",
      },
      tooltip: {
        position: "top",
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        data: ["第1周", "第2周", "第3周", "第4周", "第5周"],
        splitArea: {
          show: true,
        },
      },
      yAxis: {
        type: "category",
        data: ["指针操作", "内存管理", "中断处理", "任务调度", "IO操作"],
        splitArea: {
          show: true,
        },
      },
      visualMap: {
        min: 0,
        max: 100,
        calculable: true,
        orient: "horizontal",
        left: "center",
        bottom: "0%",
      },
      series: [
        {
          name: "掌握度",
          type: "heatmap",
          data: [
            [0, 0, 85],
            [0, 1, 90],
            [0, 2, 88],
            [0, 3, 92],
            [0, 4, 89],
            [1, 0, 75],
            [1, 1, 80],
            [1, 2, 82],
            [1, 3, 85],
            [1, 4, 78],
            [2, 0, 65],
            [2, 1, 70],
            [2, 2, 68],
            [2, 3, 72],
            [2, 4, 69],
            [3, 0, 55],
            [3, 1, 60],
            [3, 2, 58],
            [3, 3, 62],
            [3, 4, 59],
            [4, 0, 45],
            [4, 1, 50],
            [4, 2, 48],
            [4, 3, 52],
            [4, 4, 49],
          ],
          label: {
            show: true,
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    masteryChart.setOption(masteryOption);

    // 初始化成绩趋势图
    const trendChart = echarts.init(document.getElementById("trendChart"));
    const trendOption = {
      title: {
        text: "班级成绩趋势",
      },
      tooltip: {
        trigger: "axis",
      },
      legend: {
        data: ["平均分", "最高分", "最低分"],
      },
      grid: {
        left: "3%",
        right: "4%",
        bottom: "3%",
        containLabel: true,
      },
      xAxis: {
        type: "category",
        boundaryGap: false,
        data: ["第1次", "第2次", "第3次", "第4次", "第5次"],
      },
      yAxis: {
        type: "value",
        max: 100,
      },
      series: [
        {
          name: "平均分",
          type: "line",
          data: [75, 78, 80, 82, 85],
        },
        {
          name: "最高分",
          type: "line",
          data: [90, 92, 95, 94, 96],
        },
        {
          name: "最低分",
          type: "line",
          data: [60, 65, 68, 70, 72],
        },
      ],
    };
    trendChart.setOption(trendOption);

    // 初始化知识点错误分布图
    const errorChart = echarts.init(document.getElementById("errorChart"));
    const errorOption = {
      title: {
        text: "知识点错误分布",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "错误分布",
          type: "pie",
          radius: "50%",
          data: [
            { value: 35, name: "指针操作" },
            { value: 25, name: "内存管理" },
            { value: 20, name: "中断处理" },
            { value: 15, name: "任务调度" },
            { value: 5, name: "IO操作" },
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    errorChart.setOption(errorOption);

    // 清理函数
    return () => {
      masteryChart.dispose();
      trendChart.dispose();
      errorChart.dispose();
    };
  }, []);

  const knowledgePoints: KnowledgePoint[] = [
    {
      name: "指针操作",
      mastery: 75,
      exercises: 120,
      errorRate: 25,
    },
    {
      name: "内存管理",
      mastery: 82,
      exercises: 90,
      errorRate: 18,
    },
    {
      name: "中断处理",
      mastery: 68,
      exercises: 80,
      errorRate: 32,
    },
    {
      name: "任务调度",
      mastery: 85,
      exercises: 100,
      errorRate: 15,
    },
    {
      name: "IO操作",
      mastery: 78,
      exercises: 70,
      errorRate: 22,
    },
  ];

  const students: Student[] = [
    {
      id: "1",
      name: "李明",
      averageScore: 85,
      attendance: 95,
      exercises: 120,
      performance: "excellent",
    },
    {
      id: "2",
      name: "王芳",
      averageScore: 78,
      attendance: 90,
      exercises: 100,
      performance: "good",
    },
    {
      id: "3",
      name: "张伟",
      averageScore: 92,
      attendance: 98,
      exercises: 150,
      performance: "excellent",
    },
  ];

  const knowledgeColumns = [
    {
      title: "知识点",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "掌握度",
      dataIndex: "mastery",
      key: "mastery",
      render: (mastery: number) => (
        <Progress
          percent={mastery}
          size="small"
          status={mastery < 60 ? "exception" : "normal"}
        />
      ),
    },
    {
      title: "练习次数",
      dataIndex: "exercises",
      key: "exercises",
    },
    {
      title: "错误率",
      dataIndex: "errorRate",
      key: "errorRate",
      render: (errorRate: number) => (
        <Tag
          color={errorRate > 30 ? "red" : errorRate > 20 ? "orange" : "green"}
        >
          {errorRate}%
        </Tag>
      ),
    },
  ];

  const studentColumns = [
    {
      title: "姓名",
      dataIndex: "name",
      key: "name",
    },
    {
      title: "平均成绩",
      dataIndex: "averageScore",
      key: "averageScore",
      render: (score: number) => (
        <Tag color={score >= 85 ? "green" : score >= 60 ? "blue" : "red"}>
          {score}
        </Tag>
      ),
    },
    {
      title: "出勤率",
      dataIndex: "attendance",
      key: "attendance",
      render: (attendance: number) => (
        <Progress
          percent={attendance}
          size="small"
          status={attendance < 80 ? "exception" : "normal"}
        />
      ),
    },
    {
      title: "练习完成量",
      dataIndex: "exercises",
      key: "exercises",
    },
    {
      title: "综合表现",
      dataIndex: "performance",
      key: "performance",
      render: (performance: string) => {
        const colors = {
          excellent: "green",
          good: "blue",
          normal: "orange",
          poor: "red",
        };
        const texts = {
          excellent: "优秀",
          good: "良好",
          normal: "一般",
          poor: "需要改进",
        };
        return (
          <Tag color={colors[performance as keyof typeof colors]}>
            {texts[performance as keyof typeof texts]}
          </Tag>
        );
      },
    },
  ];

  return (
    <div>
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col span={12}>
          <Select
            value={selectedClass}
            onChange={setSelectedClass}
            style={{ width: 200 }}
          >
            <Option value="class1">嵌入式2301班</Option>
            <Option value="class2">物联网2302班</Option>
          </Select>
        </Col>
        <Col span={12} style={{ textAlign: "right" }}>
          <Space>
            <Select
              value={selectedTimeRange}
              onChange={setSelectedTimeRange}
              style={{ width: 120 }}
            >
              <Option value="week">本周</Option>
              <Option value="month">本月</Option>
              <Option value="semester">本学期</Option>
            </Select>
            <Button icon={<DownloadOutlined />}>导出分析报告</Button>
          </Space>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <StyledCard title="知识点掌握度分析">
            <ChartContainer id="masteryChart" />
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={12}>
          <StyledCard title="成绩趋势分析">
            <ChartContainer id="trendChart" />
          </StyledCard>
        </Col>
        <Col span={12}>
          <StyledCard title="知识点错误分布">
            <ChartContainer id="errorChart" />
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <StyledCard title="知识点详细分析">
            <Table
              columns={knowledgeColumns}
              dataSource={knowledgePoints}
              rowKey="name"
              pagination={false}
            />
          </StyledCard>
        </Col>
      </Row>

      <Row gutter={24}>
        <Col span={24}>
          <StyledCard title="学生学习情况">
            <Table
              columns={studentColumns}
              dataSource={students}
              rowKey="id"
              pagination={false}
            />
          </StyledCard>
        </Col>
      </Row>
    </div>
  );
};

export default TeacherAnalysis;
